#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/time.h>
#include <getopt.h>
#include <errno.h>
#include <unistd.h>
#include <linux/input.h>
#include <sys/ioctl.h>
#include "tslib.h"

int main(void)
{
	int i;
	int result;
	int32_t max_slots;
	struct tsdev *ts;
	struct ts_sample_mt *samp_mt[1];
	struct input_absinfo slot;

	//打开触摸屏设备，并初始化tslib
	ts = ts_setup(NULL, 0);
	if(!ts)
	{
		printf("tslib setup failed\r\n");
		return -1;
	}
	//获取触摸屏信息
	if(ioctl(ts_fd(ts), EVIOCGABS(ABS_MT_SLOT), &slot) < 0)
	{
		ts_close(ts);
		printf("get device info failed\r\n");
		return -1;
	}
	max_slots = slot.maximum + 1 - slot.minimum;
	//根据触摸点数分配缓存触摸点的内存
	samp_mt[0] = malloc(max_slots*sizeof(struct ts_sample_mt));
	if(!samp_mt[0])
	{
		ts_close(ts);
		printf("alloc memory failed\r\n");
		return -1;
	}
	
	while(1)
	{
		result = ts_read_mt(ts, samp_mt, max_slots, 1);
		if (result < 0) {
			printf("ts_read_mt err\n");
			ts_close(ts);
			free(samp_mt[0]);
			return -1;
		}
		
		for (i = 0; i < max_slots; i++)
		{
			if (samp_mt[0][i].valid)
			{
				printf("slot %d\tid=%d\tx=%d\ty=%d\r\n",
				samp_mt[0][i].slot, samp_mt[0][i].tracking_id, samp_mt[0][i].x, samp_mt[0][i].y);
			}
		}
	}
}
